﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NES
{
    internal class Cartridge
    {
        private string FileName;
        private byte ROMBanks;

        public Cartridge()
        {
            FileName = string.Empty;
            ROMBanks = 0;
        }

        public bool LoadCart(string Path, byte[] RAM, byte[] VRAM)
        {
            try
            {
                using (FileStream FS = new FileStream(Path, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader Reader = new BinaryReader(FS))
                    {
                        FileName = Path;
                        Reader.BaseStream.Seek(4, SeekOrigin.Begin);
                        ROMBanks = Reader.ReadByte();
                        Reader.BaseStream.Seek(16, SeekOrigin.Begin);
                        if (ROMBanks == 1)
                        {
                            for (int i = 0; i < 0x4000; i++) RAM[0x8000 + i] = RAM[0xC000 + i] = Reader.ReadByte();
                        }
                        else if (ROMBanks == 2)
                        {
                            for (int i = 0; i < 0x8000; i++) RAM[0x8000 + i] = Reader.ReadByte();
                        }
                        else throw new ArgumentException("Too many PRG-ROM banks");
                        for (int i = 0; i < 0x2000; i++) VRAM[i] = Reader.ReadByte();
                    }
                }
            }
            catch (Exception Exc)
            {
                throw new ArgumentException(Exc.Message);
            }

            return true;
        }
    }
}
